import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';

import { Button, Fab, TextField } from '@mui/material';
import HomeIcon from '@mui/icons-material/Home';

import { useLocalStorage } from 'react-use';

function MemoItem({ memo }) {
  const navigate = useNavigate();
  const [memoList, setMemoList] = useLocalStorage('memo-list', []);

  const [title, setTitle] = useState(memo.title);
  const [content, setContent] = useState(memo.body);

  function updateMemoList() {
    if (!title.trim() || !content.trim()) {
      toast.error('Title and content are required');
      return;
    }

    const newMemoList = memoList.map((memoItem) => {
      if (Number(memoItem.id) === Number(memo.id)) {
        return {
          ...memoItem,
          title: title.trim(),
          body: content.trim(),
        };
      }
      return memoItem;
    });

    setMemoList(newMemoList);
    toast.success('Successfully updated!');
    navigate('/');
  }

  return (
    <form style={{ textAlign: 'center' }} onSubmit={(e) => {
      e.preventDefault();
      updateMemoList();
    }}>
      <TextField
        required
        id="outlined-basic"
        label="Title"
        variant="outlined"
        value={title}
        style={{ marginBottom: '10px' }}
        onChange={(e) => setTitle(e.target.value)}
      />
      <br />
      <TextField
        required
        id="outlined-multiline-static"
        label="Content"
        multiline
        value={content}
        rows={4}
        onChange={(e) => setContent(e.target.value)}
        style={{ marginBottom: '10px' }}
      />
      <br />
      <Button type="submit" variant="contained">
        Update
      </Button>

      <Fab
        color="primary"
        aria-label="home"
        style={{ position: 'absolute', bottom: 80, right: 40 }}
        onClick={() => navigate('/')}
      >
        <HomeIcon />
      </Fab>
    </form>
  );
}

export default MemoItem;
